package com.dm.webCrawler.common.utils;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;

import com.dm.webCrawler.common.core.lang.UUID;

/**
 * ID生成器工具类
 * 
 * @author ruoyi
 */
public class IdUtils {
	/**
	 * 获取随机UUID
	 * 
	 * @return 随机UUID
	 */
	public static String randomUUID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 简化的UUID，去掉了横线
	 * 
	 * @return 简化的UUID，去掉了横线
	 */
	public static String simpleUUID() {
		return UUID.randomUUID().toString(true);
	}

	/**
	 * 获取随机UUID，使用性能更好的ThreadLocalRandom生成UUID
	 * 
	 * @return 随机UUID
	 */
	public static String fastUUID() {
		return UUID.fastUUID().toString();
	}

	/**
	 * 简化的UUID，去掉了横线，使用性能更好的ThreadLocalRandom生成UUID
	 * 
	 * @return 简化的UUID，去掉了横线
	 */
	public static String fastSimpleUUID() {
		return UUID.fastUUID().toString(true);
	}

	private static String defaultLastCode = "DA";
	private static String dateStr = null;
	private static long guid20 = 0;
	private static SimpleDateFormat dateFormatTheDate = new SimpleDateFormat("yyyyMMdd");

	/**
	 * 生成20位有序ID
	 * 
	 * @param lastCode 后缀，必须两位，可为空，为空值为DA
	 * @return
	 */
	public synchronized static String getGuid20(String lastCode) {
		if (lastCode == null || "".equals(lastCode.trim())) {
			lastCode = defaultLastCode;
		}
		if (lastCode.length()!=2) {
			throw new OutOfMemoryError("生成20位有序ID后缀值超长");
		}
		Date now = new Date();
		String nowStr = dateFormatTheDate.format(now);
		if (dateStr == null || "".equals(dateStr.trim())) {
			dateStr = nowStr;
		}
		if (!dateStr.equals(nowStr)) {
			dateStr = nowStr;
			guid20 = 0;
		}
		guid20 += 1;

		return nowStr+getInteString(guid20, 10) + lastCode;
	}

	private static String dateStr32 = null;
	private static long guid32 = 0;
	private static SimpleDateFormat dateFormat32 = new SimpleDateFormat("yyyyMMddHHmmss");

	/**
	 * 生成32位有序ID
	 * 
	 * @param lastCode 后缀，必须两位，可为空，为空值为DA
	 * @return
	 */
	public synchronized static String getGuid32(String lastCode) {
		if (lastCode == null || "".equals(lastCode.trim())) {
			lastCode = defaultLastCode;
		}
		if (lastCode.length()!=2) {
			throw new OutOfMemoryError("生成32位有序ID后缀值超长");
		}
		Date now = new Date();
		String nowStr=dateFormatTheDate.format(now);//当前日期
		if (dateStr == null || "".equals(dateStr.trim())) {
			dateStr = nowStr;
		}
		if (!dateStr.equals(nowStr)) {
			dateStr = nowStr;
			guid32 = 0;
		}
		guid32 += 1;
		String nowTimeStr = dateFormat32.format(now);//当前时间
		return nowTimeStr+getInteString(guid32, 16) + lastCode;
	}

	/**
	 * 根据number输出指定长度的数值字符串，不足前面补零
	 * 
	 * @param number
	 * @param returnLength
	 * @return
	 */
	private static String getInteString(long number, int returnLength) {
		String numberStr = String.valueOf(number);
		return String.join("", Collections.nCopies(returnLength - numberStr.length(), "0")) + numberStr;

	}
}
